package com.ndhutu.ee.util.netease;

import com.alibaba.fastjson.JSONObject;
import com.ndhutu.ee.util.StringUtil;
import okhttp3.*;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易工具类
 * @Author Shane
 * @Date 2020/6/4 14:56
 */
public class NeteaseUtil {
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static final String contentType_JSON = "application/json;charset=utf-8";
    public static final String contentType_FORM = "application/x-www-form-urlencoded;charset=utf-8";

    /**
     * checkSum校验
     * @Author Shane
     * @Date 2019/10/1616:46
     * @param
     * @return
     **/
    public static Map<String, String> getRequestHeaders(App app) throws Exception{
        Map<String, String> headers = new HashMap<String, String>();

        String nonce = StringUtil.getRandomNumberStr(6);
        String curTime = System.currentTimeMillis()/1000+"";
        String value = app.getAppSecret()+nonce+curTime;

        //计算checkSum
        MessageDigest messageDigest = MessageDigest.getInstance("sha1");
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String checkSum = buf.toString();

        headers.put("AppKey", app.getAppKey());
        headers.put("Nonce", nonce);
        headers.put("CurTime", curTime);
        headers.put("CheckSum", checkSum);
        return headers;
    }

    /**
     * post 请求
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String, Object> post(String url, Map<String, Object> params, Map<String, String> headers) throws IOException{
        String result = toResponse(url, params, headers, NeteaseUtil.contentType_FORM, "POST").body().string();
        return JSONObject.parseObject(result);
    }

    /**
     * get请求
     * @Author Shane
     * @Date 2020/4/8 12:48
     * @param
     * @return
     */
    public static String get(String url, Map<String, Object> params, Map<String, String> headers) throws IOException{
        return toResponse(url, params, headers, NeteaseUtil.contentType_FORM, "GET").body().string();
    }


    /**
     * 请求
     * @param url
     * @return
     * @throws IOException
     */
    public static Response toResponse(String url, Map<String, Object> params, Map<String, String> headers, String contentType, String method) throws IOException{
        String content = "";
        if(params != null && params.size() > 0){
            StringBuffer buff = new StringBuffer();
            for(Map.Entry<String, Object> entry : params.entrySet()){
                buff.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            content = buff.substring(1, buff.length());
        }
        RequestBody body = RequestBody.create( MediaType.parse(contentType), content);

        Request.Builder builder = new Request.Builder();
        for(Map.Entry<String, String> entry : headers.entrySet()){
            builder.addHeader(entry.getKey(), entry.getValue());
        }
        builder = builder.url(url);

        method = method.toUpperCase();
        if("POST".equals(method)){
            builder = builder.post(body);
        }else if("GET".equals(method)){

        }else if("DELETE".equals(method)){
            builder = builder.delete(body);
        }

        Request request = builder.build();
        Call call = new OkHttpClient().newCall(request);
        return call.execute();
    }
}
